<script setup lang="ts">
import { useMap } from "@/views/pipe-network/components/Map/index.vue";
import { LCircle, LPolyline } from "@vue-leaflet/vue-leaflet";
import { useMapStore } from "@/store";
import { isSamePoint } from "@/utils/map";

const mapStore = useMapStore();
const { startPointInfo, tmpPipeLines } = storeToRefs(mapStore);

const map = useMap();
const depthList = ref([]); // 存储管点的深度，用于计算平均深度
const onMapClick = (e: any) => {
  mapStore.setTmpPipeLines([...tmpPipeLines.value, e.latlng]);
};
const onDblClick = (e: any) => {
  map.off("click", onMapClick).off("dblclick", onDblClick);
  map.doubleClickZoom.enable();
  map.dragging.enable();
  mapStore.setAddedPipeLines(tmpPipeLines.value);
  mapStore.setLineDepth(getLineDepth());
};
const getLineDepth = () => {
  const len = depthList.value.length;
  const total = depthList.value.reduce((total, a) => (total += a), 0);
  return len === 0 ? 0 : total / len;
};

const initialEvents = () => {
  if (map.dragging._enabled) {
    map.on("click", onMapClick).on("dblclick", onDblClick);
    map.doubleClickZoom.disable();
    map.dragging.disable();
  }
};

onMounted(() => {
  initialEvents();
  depthList.value = [];
});
onUnmounted(() => {
  map.off("click", onMapClick);
  map.off("dblclick", onDblClick);
  map.doubleClickZoom.enable();
  map.dragging.enable();
  mapStore.setAddedPipeLines(null);
  if (mapStore.tmpPipeLines.length > 0) {
    mapStore.setTmpPipeLines([]);
    mapStore.setLineDepth(0);
  }
});
watchEffect(() => {
  if (startPointInfo?.value && tmpPipeLines.value.length > 0) {
    const { original, latlng, depth } = startPointInfo.value;
    const index = tmpPipeLines.value.findLastIndex((item) => {
      return isSamePoint(item, latlng);
    });
    if (index > -1) {
      tmpPipeLines.value[index] = original;
      if (Number.isFinite(depth)) {
        depthList.value.push(depth);
      }
    }
  }
});
watchEffect(() => {
  if (tmpPipeLines.value.length === 0) {
    initialEvents();
  }
});
</script>

<template>
  <LPolyline
    v-if="tmpPipeLines.length > 1"
    :lat-lngs="tmpPipeLines"
    color="blue"
  />
  <LCircle
    v-for="latlng in tmpPipeLines"
    :key="latlng"
    :lat-lng="latlng"
    color="red"
    :radius="5"
    weight="3"
  />
</template>

<style scoped lang="scss"></style>
